<template>
  <el-dialog
    v-model="dialogVisible"
    title="重点人口录入"
    width="800px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      v-loading="loading"
    >
      <!-- 人员基本信息 -->
      <el-divider content-position="left">人员基本信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="身份证号" prop="idCard">
            <el-input 
              v-model="form.idCard" 
              placeholder="请输入身份证号"
              @blur="handleIdCardBlur"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名">
            <el-input 
              v-model="personInfo.name" 
              placeholder="根据身份证号自动获取"
              readonly
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" v-if="personInfo.name">
        <el-col :span="8">
          <el-form-item label="性别">
            <el-input 
              :value="personInfo.gender === 1 ? '男' : personInfo.gender === 2 ? '女' : ''"
              readonly
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="出生日期">
            <el-input 
              :value="formatDate(personInfo.birthDate)"
              readonly
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系电话">
            <el-input 
              v-model="personInfo.phone"
              readonly
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 重点人口信息 -->
      <el-divider content-position="left">重点人口信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="重点人员类别" prop="category">
            <el-select v-model="form.category" placeholder="请选择重点人员类别" style="width: 100%">
              <el-option label="涉毒人员" value="涉毒人员" />
              <el-option label="涉恐人员" value="涉恐人员" />
              <el-option label="涉稳人员" value="涉稳人员" />
              <el-option label="精神病患者" value="精神病患者" />
              <el-option label="刑满释放人员" value="刑满释放人员" />
              <el-option label="社区矫正人员" value="社区矫正人员" />
              <el-option label="吸毒人员" value="吸毒人员" />
              <el-option label="肇事肇祸精神病人" value="肇事肇祸精神病人" />
              <el-option label="重点上访人员" value="重点上访人员" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="风险等级" prop="riskLevel">
            <el-select v-model="form.riskLevel" placeholder="请选择风险等级" style="width: 100%">
              <el-option label="低风险" :value="1" />
              <el-option label="中风险" :value="2" />
              <el-option label="高风险" :value="3" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="责任民警" prop="responsibleOfficer">
            <el-input v-model="form.responsibleOfficer" placeholder="请输入责任民警姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系频次" prop="contactFrequency">
            <el-select v-model="form.contactFrequency" placeholder="请选择联系频次" style="width: 100%">
              <el-option label="每天一次" value="每天一次" />
              <el-option label="每周一次" value="每周一次" />
              <el-option label="每月一次" value="每月一次" />
              <el-option label="每季度一次" value="每季度一次" />
              <el-option label="不定期" value="不定期" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="监管原因" prop="monitorReason">
        <el-input
          v-model="form.monitorReason"
          type="textarea"
          :rows="3"
          placeholder="请输入监管原因"
        />
      </el-form-item>

      <el-form-item label="监管措施" prop="monitorMeasures">
        <el-input
          v-model="form.monitorMeasures"
          type="textarea"
          :rows="3"
          placeholder="请输入监管措施"
        />
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="最后联系日期">
            <el-date-picker
              v-model="form.lastContactDate"
              type="date"
              placeholder="请选择最后联系日期"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="备注">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="2"
          placeholder="请输入备注信息（可选）"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确认录入
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { API_BASE_URL } from '@/config/api'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const formRef = ref()
const loading = ref(false)

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 人员基本信息
const personInfo = reactive({
  name: '',
  gender: null,
  birthDate: '',
  phone: '',
  ethnicity: '',
  occupation: ''
})

// 表单数据 - 对应后端 KeyPersonnelBO
const form = reactive({
  idCard: '',
  category: '',
  riskLevel: null,
  monitorReason: '',
  monitorMeasures: '',
  responsibleOfficer: '',
  contactFrequency: '',
  lastContactDate: null,
  remark: ''
})

// 表单验证规则
const rules = {
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '身份证号格式不正确', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择重点人员类别', trigger: 'change' }
  ],
  riskLevel: [
    { required: true, message: '请选择风险等级', trigger: 'change' }
  ],
  monitorReason: [
    { required: true, message: '请输入监管原因', trigger: 'blur' }
  ],
  monitorMeasures: [
    { required: true, message: '请输入监管措施', trigger: 'blur' }
  ],
  responsibleOfficer: [
    { required: true, message: '请输入责任民警', trigger: 'blur' }
  ],
  contactFrequency: [
    { required: true, message: '请选择联系频次', trigger: 'change' }
  ]
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString()
}

// 身份证号失焦事件 - 获取人员信息
const handleIdCardBlur = async () => {
  if (!form.idCard || form.idCard.length !== 18) {
    return
  }

  try {
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.error('请先登录')
      return
    }

    const response = await axios.get(`${API_BASE_URL}/person/getByIdCard`, {
      params: { idCard: form.idCard },
      headers: { 'token': token }
    })

    if (response.data.status === 200 && response.data.data) {
      const person = response.data.data
      personInfo.name = person.name || ''
      personInfo.gender = person.gender || null
      personInfo.birthDate = person.birthDate || ''
      personInfo.phone = person.phone || ''
      personInfo.ethnicity = person.ethnicity || ''
      personInfo.occupation = person.occupation || ''
    } else {
      ElMessage.warning('未找到该身份证号对应的人员信息')
      // 清空人员信息
      Object.keys(personInfo).forEach(key => {
        personInfo[key] = key === 'gender' ? null : ''
      })
    }
  } catch (error) {
    console.error('获取人员信息失败:', error)
    ElMessage.error('获取人员信息失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    if (!personInfo.name) {
      ElMessage.error('请先输入有效的身份证号获取人员信息')
      return
    }
    
    loading.value = true
    
    try {
      const token = localStorage.getItem('token')
      if (!token) {
        ElMessage.error('请先登录')
        return
      }

      console.log('发送重点人口录入请求，数据:', form)
      
      // 发送请求到后端
      const response = await axios.post(`${API_BASE_URL}/key-personnel/input`, form, {
        headers: {
          'token': token,
          'Content-Type': 'application/json'
        }
      })
      
      console.log('重点人口录入响应:', response.data)
      
      // 处理响应结果
      const result = response.data
      
      if (result.status === 200) {
        // 录入成功
        ElMessage.success(result.msg || '重点人口录入成功')
        emit('success')
        handleClose()
      } else {
        // 录入失败
        ElMessage.error(result.msg || '重点人口录入失败')
      }
      
    } catch (error) {
      console.error('重点人口录入请求出错:', error)
      
      if (error.response) {
        // 服务器返回了错误状态码
        const errorMsg = error.response.data?.msg || '服务器错误，请稍后重试'
        ElMessage.error(errorMsg)
      } else if (error.request) {
        // 请求发出但没有收到响应
        ElMessage.error('网络连接失败，请检查网络')
      } else {
        // 其他错误
        ElMessage.error('重点人口录入失败: ' + error.message)
      }
    } finally {
      loading.value = false
    }
  })
}

// 关闭对话框
const handleClose = () => {
  // 重置表单
  formRef.value?.resetFields()
  // 清空人员信息
  Object.keys(personInfo).forEach(key => {
    personInfo[key] = key === 'gender' ? null : ''
  })
  // 关闭对话框
  dialogVisible.value = false
}

// 监听对话框关闭，重置表单
watch(dialogVisible, (newVal) => {
  if (!newVal) {
    // 延迟重置，确保对话框完全关闭
    setTimeout(() => {
      formRef.value?.resetFields()
      Object.keys(personInfo).forEach(key => {
        personInfo[key] = key === 'gender' ? null : ''
      })
    }, 300)
  }
})
</script>

<style lang="scss" scoped>
.el-divider {
  margin: 20px 0;
}

.el-divider__text {
  font-weight: 600;
  color: #409eff;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>